<script setup lang="ts">
// import { NButton, NConfigProvider, darkTheme } from 'naive-ui'
// import { watch } from 'vue';
// import {useTheme} from "./hooks/useTheme"
import { useNet } from "@/stores/net";
import { Bus, CHART_CHAIN_SUBSCRIBE, CHART_KLINE_SUBSCRIBE, CLOSE, CONN_ACTIVITY, CONN_CLEVER, BIGTRADE, CONN_RANK, CONN_STATUS, KLINE_RANK_FLUCTUATION, KLINE_RANK_FLUCTUATION_MN5, PING, START_CONN, TRADE_DOUBLE, DAY_STATE } from "@/connetion/Bus";
import { useKline } from "./stores/kline";
import { onMounted, onBeforeMount, ref, watch } from "vue";
// import { PING_INTERVAL_TIME } from "./connetion/PingBroadcast";
import Rock from "@/components/rock/index.vue"
import { useActivity } from "./stores/activity";
import { useLayout } from "@/stores/layout";
import { useRank } from "./stores/rank";
import { useClever } from "./stores/clever";
import { useUser } from "./stores/user";
import { Conn } from "./connetion/Conn";
import { toast } from "./components/toast/toast";
import { getURLParams } from "./comm/tooler";
import { useRoute, useRouter } from "vue-router";
import { useAccount } from "./stores/account";
import { URL_GOOGLE_CALLBACK, URL_TWITTER_CALLBACK } from "./comm/api";
import { get, post } from "./comm/request";
import { useCore } from "./hooks/useCore";
import { Core } from "./comm/Core";
import { useTokens } from "./stores/tokens";
import { useI18n } from "vue-i18n";
import { useConn } from "./hooks/useConn";
import { initChartConfig } from "@/components/chart/config";
import { callObj } from "@/comm/loginSucCall";
import { formatTimestamp } from "./comm/format";
import { Notify } from "./components/y-notify/script";
// import {  } from "fs";
// import { PING_INTERVAL_TIME } from "./connetion/PingBroadcast";
const net = useNet();
const kline = useKline();
const activity = useActivity();
const rank = useRank();
const clever = useClever();
const user = useUser();
const layout = useLayout();
const account = useAccount();
const tokens = useTokens();
const router = useRouter();
const route = useRoute();
// let cur = Date.now();
const core = useCore();
// const conn = useConn();
let initCount = 0;

onBeforeMount(async () => {
    console.log(kline)
    initChartConfig(kline);

    // await core.init();
    // if(route.name == "home"){
    //     kline.changeCurCoin(kline.map[0]);
    // }
    // tokens.init();
    // await Conn.ins.start();
    // Bus.emit(CHART_CHAIN_SUBSCRIBE, kline.curCoin.tokenAddress);
});
const { t, locale } = useI18n();

onMounted(async () => {
    // console.error("start app")
    user.checkUserLogin();
    if (window.innerWidth < 1280) {
        layout.closeNesOpen()
    } else {
        layout.openNesOpen()

    }
    account.isMetaMaskInstall()
    console.log("start mount", router);
    setTimeout(() => {
        Core.ins.hideLoading();

        // Notify.alert("登录成功");

    }, 1000);
    /* 
     webscocket焦点切换后，重新订阅
    */
    document.addEventListener("visibilitychange", socketPing);
    // user.ping();

    await getUserAgent()
    await core.init();
    if (location.pathname == "/") {
        localStorage.setItem("init", "1");
    } else {
        localStorage.setItem("init", "0");
    }

    let type = "";
    if (location.href.includes("/coin")) {
        type = "coin";
    }
    if (location.href.includes("/entity")) {
        type = "entity";
    }
    if (type) {
        let t = location.pathname.split(`/${type}/`).pop() + "";
        kline.changeCurCoinByName(t);
    } else {
        // kline.changeCurCoinByName();
        let ctype = localStorage.getItem("K_TYPE");
        if (ctype) {
            kline.changeCurCoinByName(ctype);
        }
        else {
            kline.changeCurCoin(kline.map[0]);
        }
    }

    setTimeout(() => {
        if(user.info && localStorage.getItem("willReward") == "1"){
            account.changePopRegisterSuccess(true);
        }
    }, 300);

    tokens.init();

    await Conn.ins.start();
    Bus.emit(CHART_CHAIN_SUBSCRIBE, kline.curCoin.tokenAddress);

    Core.ins.hideLoading();

    if (localStorage.getItem("language") !== null) {
        locale.value = localStorage.getItem("language")!;
        // locale.value = "en";
    } else {
        localStorage.setItem("language", locale.value);
        // console.log('yzt____本地语言读取错误', locale);
    }
    const param = getURLParams();
    if (param && param.recommend) {
        // localStorage.setItem("code", param.recommend);
        user.changeRecommend(param.recommend);
        account.changePopRegister(true);
    }

    // Conn.ins.start();
});


watch(()=>user.info, (val)=>{
    console.warn("@@@ user info", val);
    if(val){
        if(user.hasRegisterMission){
            account.changePopRegisterSuccess(true);
        }
        user.ping();
    }
})

const socketPing = async () => {
    if (document.visibilityState == "hidden") {
        console.log("################ 标签页隐藏");
        user.changeInPage(false); 
    } else {
        // console.log('################ 标签页显示', Conn.ins.socket.readyState)
        console.log("标签页打开", Conn.ins);
        //判断webscocket是否断开 如果断开重新连接
        if (!Conn.ins?.socket || Conn.ins.socket.readyState == 0) {
            console.log("################ 标签页显示并且 webscocket断开 重新连接");
            await Conn.ins.start();
        }
        user.changeInPage(true); 
    }
};

Bus.on(DAY_STATE, (res: any) => {
    // console.log("DAY_STATE", res);
    // if (kline.curCoin && res.s == kline.curCoin.symbol) {
    //     // isUp.value = res.c >= lastPrice.value;
    //     // lastPrice.value = res.c;
    //     day.h = res.h;
    //     day.l = res.l;
    //     day.v = res.v;
    //     day.n = res.n;
    //     // day.c = res.c;
    //     day.p = res.p;
    //     day.P = res.P;
    //     day.q = res.q;
    // }
    let item = kline.map.find(i => i.symbol == res.s);
    if (item) {
        item.priceChangePercent = res.P; //涨跌幅
        item.lastPrice = res.c; //最新价
        item.quoteVolume = res.q;
    }
});

Bus.on(PING, (val: any) => {
    net.changeSocketTimeout(val);
});

Bus.on(CONN_STATUS, (val: any) => {
    net.changeStatus(val);
});

Bus.on(CONN_ACTIVITY, (val: any) => {
    // activity.changeActivitys(val);
    activity.pushActivitys(val);
});

Bus.on(CONN_RANK, (val: any) => {
    rank.changeRanks(val);
    // console.log(val,'REAL_TIME_BIG_TURNOVER')

});
// 监听 大额交易推送数据
Bus.on(BIGTRADE, (val: any) => {
    // layout.changeSnackbar(true)
    layout.setText(formatTimestamp(val[0].T), val[0], 'big')
});
// 监听 聪明钱交易推送数据
Bus.on(TRADE_DOUBLE, (val: any) => {
    // console.log(val,"崇明钱");
    console.log('聪明钱推送')
    // layout.changeSnackbar(true)
    layout.setText('', val, 'wise')
});
Bus.on(KLINE_RANK_FLUCTUATION, (val: any) => {
    rank.resetWave(val);
})

Bus.on(KLINE_RANK_FLUCTUATION_MN5, (val: any) => {
    rank.resetWaveM5(val);
})

Bus.on(CONN_CLEVER, (val: any) => {
    clever.changeClevers(val);
});

Bus.on(START_CONN, str => {
    // initCount++;
    // if (initCount >= 2) {
    //     Conn.ins.start();
    //     setTimeout(() => {
    //         Bus.emit(CHART_KLINE_SUBSCRIBE, kline.param);
    //     }, 900);
    // }

    // Conn.ins.start();
    setTimeout(() => {
        Bus.emit(CHART_KLINE_SUBSCRIBE, kline.param);
    }, 900);
});


function loginMobile() {
    if (layout.isMobile && !!user.info) {
        if (localStorage.getItem("willJump") == "1") {
            if (location.href.includes("/reward") == false) {
                localStorage.removeItem("willJump");
                location.href = "/reward";
            }
        }
    }
}

const login = (param: any) => {
    post(URL_GOOGLE_CALLBACK, param, true, 1)
        .then(async (res: any) => {
            // console.warn("res----");
            // console.warn("Google登录验证结果", res);
            if (res.code == 200) {
                let isLogin: any = await user.checkLogin();
                //绑定
                if (isLogin) {
                    // toast("绑定Google成功");
                    Notify.alert(t("message.accouts.bg"));
                    account.changePopLogin(false);
                    account.changePopRegister(false);
                }
                //登录
                else {
                    localStorage.setItem("token", res.data.token);
                    // toast("登录成功");
                    Notify.alert(t("message.accouts.ls"));
                    account.changePopLogin(false);
                    account.changePopRegister(false);

                    callObj.callfun();
                    if (res.data.firstLogin) {
                        account.changePopRegisterSuccess(true);
                    }
                }

                // let isLogin = await user.checkLogin();
                // if (isLogin) {
                //     console.log("已经登录，绑定google完成");
                //     toast("绑定google完成");
                //     user.getUserInfo();
                //     return;
                // }
                // localStorage.setItem("token", res.data);
                let err = await user.getUserInfo();
                if (!err) {
                    // toast(err);
                } else {
                    console.log("关闭弹窗");
                    account.changePopLogin(false);
                    toast(err);
                }

                loginMobile();
            } else {
                toast(res.info);
            }
        })
        .catch(e => {
            // console.warn("err----");
            // console.warn(e);
            // toast(res.info);
            // toast(t("message.accouts.sb"));
        });
};

console.log(location.href);

function getUserAgent() {
    const userAgent = navigator.userAgent;
    if (/Mobile|Android|iPhone|iP(ad|od)/i.test(userAgent)) {
        // console.log('移动端')
        layout.closeNesOpen()
    } else {
        
    }
}

function extractValuesFromURL(url: string) {
    let obj = url.match(/state=([^&]+)&access_token=([^&]+)/);
    if (obj?.length == 3) {
        return {
            state: obj[1],
            access_token: obj[2]
        };
    }
    return null;
}

function googleLogin() {
    let param = extractValuesFromURL(location.href);
    login(param);
}

function checkJoin() {
    return localStorage.getItem("join") == "1";
}
window.addEventListener("resize", (e) => {
    // console.log("尺寸变化",window.innerWidth,window.innerWidth<1200)
    if(!user.info) return
    if (window.innerWidth < 1280) {
        layout.closeNesOpen()
    } else {
        layout.openNesOpen()

    }
})

window.addEventListener("message", async function (event) {
    //可以通过event.origin  判断消息来源
    // console.log("href", event.data);
    if (typeof event.data !== "string") return;

    // let isLogin = await user.checkLogin();
    let isLogin = !!user.info;
    if (event.data.indexOf("google.html") != -1) {
        // https://alpha.chainingview.io/oauth/google#/
        // const map = new URLSearchParams(event.data.split("oauth/google#/").pop());

        localStorage.setItem("googleGet", event.data);

        const map = new URLSearchParams(event.data.split("#").pop());
        const state = map.get("state");
        const access_token = map.get("access_token");

        const obj: any = {
            state,
            access_token,
            type: isLogin ? 2 : 1
        };

        if (checkJoin()) {
            obj.type = 3;
            localStorage.removeItem("join")
        }

        // const param = getURLParams();
        let recommend = localStorage.getItem("code");
        if (recommend) {
            obj.recommendCode = recommend;
        }
        login(obj);
    } else if (event.data.indexOf("twitter") != -1) {

        localStorage.setItem("twitterGet", event.data);
        // const url = URL_TWITTER_CALLBACK + "?" + event.data.split("?").pop();
        // http://alpha.chainingview.io/oauth/twitter?oauth_token=sIBgPAAAAAABqrFtAAABjIx2wFA&oauth_verifier=rF6iVA2Gj1Ks4jBJJik7JZKeFKGidcfj

        var url = event.data;
        let urlStr = url.split("?")[1];
        const urlSearchParams = new URLSearchParams(urlStr);
        const result = Object.fromEntries(urlSearchParams.entries());

        var obj: any = {
            oauth_token: result.oauth_token,
            oauth_verifier: result.oauth_verifier,
            type: isLogin ? 2 : 1
        };

        if (checkJoin()) {
            obj.type = 3;
            localStorage.removeItem("join")
        }

        let recommend = localStorage.getItem("code");
        if (recommend) {
            obj.recommendCode = recommend;
        }

        post(URL_TWITTER_CALLBACK, obj, true).then(async (res: any) => {
            console.log(res, "twitter login");
            if (res.code == 200) {
                // let isLogin = await user.checkLogin()
                if (obj.type == 3) {
                    account.changeJoinToken(res.data);

                    return;
                }
                //绑定
                if (isLogin) {
                    // toast("绑定twitter成功");
                    Notify.alert(t("message.accouts.bt"));
                    account.changePopLogin(false);
                    account.changePopRegister(false);
                }
                //登录
                else {
                    localStorage.setItem("token", res.data.token);
                    Notify.alert(t("message.accouts.ls"));

                    account.changePopLogin(false);
                    account.changePopRegister(false);
                    callObj.callfun();

                    if (res.data.firstLogin) {
                        account.changePopRegisterSuccess(true);
                    }
                }
                localStorage.removeItem("code");
                // let isLogin = await user.checkLogin();
                // if (isLogin) {
                //     console.log("已经登录，绑定twitter完成");
                //     toast("绑定twitter完成");
                //     user.getUserInfo();
                //     return;
                // }
                // localStorage.setItem("token", res.data);
                let err = await user.getUserInfo();
                if (!err) {
                    // toast(err);
                } else {
                    // console.log("关闭弹窗");
                    account.changePopLogin(false);
                    account.changePopRegister(false);
                }
                loginMobile();
            } else {
                toast(res.info);
            }
        }).catch(e => {
            // toast(t("message.accouts.sb"));
        });
    }
});
</script>

<template>
    <!-- <div class="loading" v-if="loading"></div> -->
    <v-app>
        <Rock></Rock>
        <router-view></router-view>
    </v-app>
</template>

<style lang="less" scoped>
.logo {
    height: 6em;
    padding: 1.5em;
    will-change: filter;

    &:hover {
        filter: drop-shadow(0 0 2em #646cffaa);
    }
}
</style>
